package com.weihao.sd.utils;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SmsClientUtils {

	private static Logger logger = LoggerFactory
			.getLogger(SmsClientUtils.class);
	
	public final static String ERROR_CODE = "errcode";
	public final static String ERROR_MSG = "errmsg";

	private static HttpClient httpClient = new DefaultHttpClient();

	private static String product = null;

	private static String extno = null;

	private static long startTime = 0L;

	private static long endTime = 0L;

	public static JSONObject postSms(String url, SmsDto smsDto) throws JSONException {

		logger.info("httpclient postSms开始。");

		JSONObject resJson = null;
		String errorCode = "0";
		String errorMsg = "";

		HttpPost method = new HttpPost(url);
		
//		HttpHost proxy = new HttpHost("10.108.25.100", 808);    
//        method.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 

		// 使用NameValuePair来保存要传递的Post参数
		List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("account", smsDto.getAccount()));
		postParameters.add(new BasicNameValuePair("pswd", smsDto.getPswd()));
		postParameters
				.add(new BasicNameValuePair("mobile", smsDto.getMobiles()));
		postParameters.add(new BasicNameValuePair("needstatus", String
				.valueOf(smsDto.isNeedstatus())));
		postParameters.add(new BasicNameValuePair("msg", smsDto.getContent()));
		postParameters.add(new BasicNameValuePair("product", product));
		postParameters.add(new BasicNameValuePair("extno", extno));

		try {
			startTime = System.currentTimeMillis();

			// 实例化UrlEncodedFormEntity对象
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters,"UTF-8");

			// 使用HttpPost对象来设置UrlEncodedFormEntity的Entity
			method.setEntity(formEntity);
			HttpResponse result = httpClient.execute(method);

			endTime = System.currentTimeMillis();
			int statusCode = result.getStatusLine().getStatusCode();
			logger.info("statusCode:" + statusCode);
			logger.info("调用API 花费时间(单位：毫秒)：" + (endTime - startTime));
			
			if (statusCode == HttpStatus.SC_OK) {
				String returnMsg = EntityUtils.toString(result.getEntity(), "UTF-8");
				logger.info("反回消息串：" + returnMsg);
				resJson = new JSONObject();
				if(!StringUtils.isEmpty(returnMsg)){
					String[] split = returnMsg.split(",");
					if(null!=split && StringUtils.isNotEmpty(split[0])){
						resJson.put("resptime", split[0]);
					}
					if(StringUtils.isNotEmpty(split[1])){
						String[] split2 = split[1].split("\n");
						if(null != split2){
							resJson.put("respstatus", split2[0]);
							if (split2.length==2)
								resJson.put("smsid", split2[1]);
						}
					}
				}
				
				return resJson;
			}

		} catch (ClientProtocolException e) {
			errorMsg = "接口调用失败:" + url;
			logger.error("接口调用失败", e);
			// e.printStackTrace();
		} catch (IOException e) {
			errorMsg = "IO异常，网络传输异常";
			logger.error("IO异常,网络传输异常", e);
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		resJson.put(ERROR_CODE, errorCode);
		resJson.put(ERROR_MSG, errorMsg);
		return resJson;
	}

	public static String getSms(String url) {
		logger.info("httpclient getSms开始。");
		
		String retrunMsg = "";
		HttpGet method = new HttpGet(url);
		
//        HttpHost proxy = new HttpHost("10.108.25.100", 808);    
//        method.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);    
        //设置代理结束 

		try {
			startTime = System.currentTimeMillis();

			HttpResponse result = httpClient.execute(method);

			endTime = System.currentTimeMillis();
			int statusCode = result.getStatusLine().getStatusCode();

			logger.info("statusCode:" + statusCode);
			logger.info("调用API 花费时间(单位：毫秒)：" + (endTime - startTime));
			if (statusCode == HttpStatus.SC_OK) {
				retrunMsg = EntityUtils.toString(result.getEntity(),
						"UTF-8");
				return retrunMsg;
			}

		} catch (ClientProtocolException e) {
			retrunMsg = "接口调用失败:" + url;
			logger.error("接口调用失败", e);
			// e.printStackTrace();
		} catch (ParseException e) {
			retrunMsg = "结果转换失败";
			logger.error("结果转换失败", e);
			// e.printStackTrace();
		} catch (IOException e) {
			retrunMsg = "IO异常，网络传输异常";
			logger.error("IO异常,网络传输异常", e);
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return retrunMsg;

	}

}
